<template>
  <div
    ref="myChartsRef"
    :style="{ height: height, width: width }"
    :option="option"
  ></div>
</template>

<script setup lang="ts">
import { init } from "echarts";
import {
  ref,
  watch,
  defineProps,
  onMounted,
  onBeforeUnmount
} from "vue";

const props = defineProps({
  width: "100%",
  height: {
    type: Number,
    default: 450
  },
  option: {
    type: Object,
    default: {}
  }
});

const myChartsRef = ref(null);
let myChart = null;
let timer = null;

// 初始化echarts
const initChart = () => {
  myChart = init(myChartsRef.value);
  // 拿到option配置项，渲染echarts
  myChart?.setOption(props.option, true);
  myChart.resize({
    height: props.height
  });
};

// 重新渲染echarts
const resizeChart = () => {
  clearTimeout(timer);
  timer = setTimeout(() => {
    if (myChart) {
      myChart.resize({
        width: props.width,
        height: props.height,
      });
    }
  }, 500);
};

onMounted(() => {
  initChart();
  window.addEventListener("resize", resizeChart);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeChart);
  clearTimeout(timer);
  timer = 0;
});

watch(
  props.option,
  () => {
    initChart();
  },
  {
    deep: true
  }
);
</script>
